package com.foreknow.controller;

import com.foreknow.model.Guestbook;
import com.foreknow.service.AdminService;
import com.foreknow.service.BusinessService;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.AdminServiceImpl;
import com.foreknow.service.impl.BusinessServiceImpl;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author shkstart
 * @create 2021-08-19 14:13
 */
public class AddMessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        doGet(req,resp);
        resp.setContentType("text/html;charset=utf-8");
        //设置客户端向服务器端发送请求的字符编码集
        req.setCharacterEncoding("utf-8");
        PrintWriter out=resp.getWriter();

        //获取请求参数
        String username = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        Date date = new Date();

//获取年月日时分秒，也可以只获取其中的一个，其中的中文汉字可以改为-
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createdTime = formatter.format(date);

        GuestbookService guestbookService=new GuestbookServiceImpl();


        Guestbook guestbook=new Guestbook(username,phone,email,title,content,createdTime);

        boolean add = guestbookService.add(guestbook);
        if(add){
//            out.println("添加成功");
            //超链接必须加Application context
//            out.println("<a href='/ManagerSystem/show'>查看所有留言</a>");
//            //如果添加成功了直接转发资源     请求转发
            RequestDispatcher rd = req.getRequestDispatcher("/user/manager");
            rd.forward(req,resp);
//            req.getRequestDispatcher("/show").forward(req,resp);
            //重定向
//            req.getContextPath();  //获取到工程名路径
//            resp.sendRedirect(req.getContextPath()+"/show");    //站内资源
//                resp.sendRedirect("");
        }else {
            out.println("添加失败");
        }


    }
}
